package com.eicas.config;

import com.eicas.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author: Administrator
 * @since: 2023/2/10 09:27
 * @description: 校验传入的token满足jwt的规范，若没有传token则交给下一层过滤
 */
@Configuration
public class ResolveTokenFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String jwt = resolveToken(request);
        if(Objects.isNull(jwt)){
            return chain.filter(exchange);
        }
        ServerHttpRequest build = exchange.getRequest().mutate().header(Constant.AUTHORIZATION_HEADER, jwt).build();
        exchange = exchange.mutate().request(build).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * Get token from header.
     */
    private String resolveToken(ServerHttpRequest request) {
        String bearerToken = request.getHeaders().getFirst(Constant.AUTHORIZATION_HEADER);
        if (StringUtils.isNotBlank(bearerToken)) {
            validatePrefix(bearerToken);
            return bearerToken.substring(Constant.TOKEN_PREFIX.length());
        }
        return null;
    }

    private void validatePrefix(String bearerToken) {
        if(!bearerToken.startsWith(Constant.TOKEN_PREFIX)){
            //一般项目前端不会校验不通过，异常信息可以不用处理
            throw new IllegalArgumentException("非法请求，token异常。");
        }
    }
}
